package com.itheima.vms.domain.po;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.itheima.vms.mapper.ItemMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ItemService {
    @Autowired
    private ItemMapper itemMapper;

    public List<Map<String, Object>> getItemList() {
        // 创建分页对象
        Page<Map<String, Object>> page = new Page<>(1, 10);

        // 创建查询条件
        QueryWrapper<Map<String, Object>> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del", 0);
        
        // 执行分页查询
        List<Map<String, Object>> results = itemMapper.page(page, queryWrapper);
        
        // 创建结果列表
        List<Map<String, Object>> finalResults = new ArrayList<>();
        
        // 使用Map存储每个商品的主信息
        Map<Integer, Map<String, Object>> itemMap = new HashMap<>();
        
        for (Map<String, Object> row : results) {
            Integer spuId = (Integer) row.get("id");
            
            // 如果该商品还没有在map中，创建新的条目
            if (!itemMap.containsKey(spuId)) {
                Map<String, Object> item = new HashMap<>();
                item.put("id", spuId);
                item.put("code", row.get("code"));
                item.put("title", row.get("title"));
                item.put("categoryName", row.get("categoryName"));
                item.put("description", row.get("description"));
                item.put("supplierName", row.get("supplierName"));
                item.put("brandName", row.get("brandName"));
                item.put("skuList", new ArrayList<>());
                itemMap.put(spuId, item);
            }
            
            // 获取商品的主信息
            Map<String, Object> item = itemMap.get(spuId);
            Map<String, Object> sku = new HashMap<>();
            sku.put("skuId", row.get("skuId"));
            sku.put("spuId", row.get("spuId"));
            sku.put("skuTitle", row.get("skuTitle"));
            sku.put("price", row.get("price"));
            sku.put("realPrice", row.get("realPrice"));
            sku.put("code_code", row.get("code_code"));
            sku.put("productWeight", row.get("productWeight"));
            sku.put("productLength", row.get("productLength"));
            sku.put("productWidth", row.get("productWidth"));
            sku.put("productHeight", row.get("productHeight"));
            sku.put("productVolume", row.get("productVolume"));
            
            // 添加到skuList
            ((List<Map<String, Object>>) item.get("skuList")).add(sku);
        }
        
        // 将map转换为list
        return new ArrayList<>(itemMap.values());
    }
}
